<?php

namespace App\Http\Middleware;

use Closure;
use Zhuzhichao\IpLocationZh\Ip;
use App\Models\System\Region as RegionModel;

class Region
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$this->isTopDomain($request) && $initials = $this->urlMatch($request)) {
            $params = ['initials' => $initials];
        } else {
            $params = ['name' => $this->getIpMatch($request)];
        }
        $region = $this->getCity($params);
        if ($region) {
            \Config::set('region.region.model', $region);
            \Config::set('region.region.city', $region->name);
            \Config::set('region.region.model_id', $region->id);
            \Config::set('region.region.url', generate_top_url('', $region->initials));
        }
        return $next($request);
    }

    private function getIpMatch($request)
    {
        $ip = Ip::find($request->ip());
        return $ip[2] ?? '';
    }

    private function urlMatch($request)
    {
        $url = $request->url();
        preg_match("#http://(.*?)\.#i", $url, $match);
        return $match[1];
    }

    private function getCity($params = [])
    {
        return RegionModel::where($params)->where('level', 2)->first();
    }

    protected function isTopDomain($request)
    {
        return in_array($request->getHost(), config('urls.prefix'));
    }
}
